/**
 * SQL模板管理器 - 核心类
 * 负责数据管理、API调用和基础功能
 */
class TemplateManager {
    constructor() {
        this.templates = [];
        this.filteredTemplates = [];
        this.currentDeleteId = null;
        this.searchTimeout = null;
        this.initializeElements();
        this.bindEvents();
        this.loadTemplates();
        this.initializeDarkMode();
        this.bindModalEvents();
    }

    initializeElements() {
        // 基础元素
        this.templatesContainer = document.getElementById('templatesContainer');
        this.loadingIndicator = document.getElementById('loadingIndicator');
        this.emptyState = document.getElementById('emptyState');
        this.noSearchResults = document.getElementById('noSearchResults');
        this.templateCount = document.getElementById('templateCount');
        this.searchInput = document.getElementById('searchInput');
        this.refreshBtn = document.getElementById('refreshBtn');
        this.darkModeToggle = document.getElementById('darkModeToggle');
        
        // 模态框元素
        this.templateModal = document.getElementById('templateModal');
        this.modalTitle = document.getElementById('modalTitle');
        this.modalContent = document.getElementById('modalContent');
        this.closeModalBtn = document.getElementById('closeModalBtn');
        this.deleteModal = document.getElementById('deleteModal');
        this.deleteTemplateName = document.getElementById('deleteTemplateName');
        this.cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
        this.confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
        
        // 导入导出相关元素
        this.importBtn = document.getElementById('importBtn');
        this.exportBtn = document.getElementById('exportBtn');
        this.importModal = document.getElementById('importModal');
        this.closeImportModal = document.getElementById('closeImportModal');
        this.importFileInput = document.getElementById('importFileInput');
        this.fileDropZone = document.getElementById('fileDropZone');
        this.selectedFileName = document.getElementById('selectedFileName');
        this.skipExisting = document.getElementById('skipExisting');
        this.validateFormat = document.getElementById('validateFormat');
        this.previewSection = document.getElementById('previewSection');
        this.previewContent = document.getElementById('previewContent');
        this.importProgress = document.getElementById('importProgress');
        this.progressBar = document.getElementById('progressBar');
        this.progressText = document.getElementById('progressText');
        this.cancelImportBtn = document.getElementById('cancelImportBtn');
        this.startImportBtn = document.getElementById('startImportBtn');
    }

    bindEvents() {
        // 基础事件
        this.refreshBtn.addEventListener('click', () => this.loadTemplates());
        this.searchInput.addEventListener('input', (e) => this.handleSearch(e.target.value));
        this.closeModalBtn.addEventListener('click', () => this.hideModal());
        this.cancelDeleteBtn.addEventListener('click', () => this.hideDeleteModal());
        this.confirmDeleteBtn.addEventListener('click', () => this.confirmDelete());
        this.darkModeToggle.addEventListener('click', () => this.toggleDarkMode());
        
        // 清空所有模板按钮事件
        const clearAllBtn = document.getElementById('clearAllBtn');
        const cancelClearAllBtn = document.getElementById('cancelClearAllBtn');
        const confirmClearAllBtn = document.getElementById('confirmClearAllBtn');
        
        if (clearAllBtn) {
            clearAllBtn.addEventListener('click', () => this.showClearAllModal());
        }
        if (cancelClearAllBtn) {
            cancelClearAllBtn.addEventListener('click', () => this.hideClearAllModal());
        }
        if (confirmClearAllBtn) {
            confirmClearAllBtn.addEventListener('click', () => this.confirmClearAll());
        }
        
        // 添加模板和相似性搜索按钮事件
        const addTemplateBtn = document.getElementById('addTemplateBtn');
        const similarSearchBtn = document.getElementById('similarSearchBtn');
        
        if (addTemplateBtn) {
            addTemplateBtn.addEventListener('click', () => this.showAddTemplateModal());
        }
        if (similarSearchBtn) {
            similarSearchBtn.addEventListener('click', () => this.showSimilarSearchModal());
        }
        
        // 导入导出按钮事件
        if (this.importBtn) {
            this.importBtn.addEventListener('click', () => this.showImportModal());
        }
        if (this.exportBtn) {
            this.exportBtn.addEventListener('click', () => this.exportTemplates());
        }
        
        // 导入模态框事件
        if (this.closeImportModal) {
            this.closeImportModal.addEventListener('click', () => this.hideImportModal());
        }
        if (this.cancelImportBtn) {
            this.cancelImportBtn.addEventListener('click', () => this.hideImportModal());
        }
        if (this.startImportBtn) {
            this.startImportBtn.addEventListener('click', () => this.startImport());
        }
        if (this.fileDropZone) {
            this.fileDropZone.addEventListener('click', () => this.importFileInput.click());
        }
        if (this.importFileInput) {
            this.importFileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        }
        
        // 拖拽事件
        if (this.fileDropZone) {
            this.fileDropZone.addEventListener('dragover', (e) => this.handleDragOver(e));
            this.fileDropZone.addEventListener('drop', (e) => this.handleFileDrop(e));
        }
        
        // 点击模态框外部关闭
        this.templateModal.addEventListener('click', (e) => {
            if (e.target === this.templateModal) this.hideModal();
        });
        this.deleteModal.addEventListener('click', (e) => {
            if (e.target === this.deleteModal) this.hideDeleteModal();
        });
        if (this.importModal) {
            this.importModal.addEventListener('click', (e) => {
                if (e.target === this.importModal) this.hideImportModal();
            });
        }
    }

    // 深色模式
    updateThemeIcon(isDark) {
        const lightIcon = document.getElementById('lightModeIcon');
        const darkIcon = document.getElementById('darkModeIcon');
        
        if (isDark) {
            // 暗黑模式：显示半月图标
            lightIcon.classList.add('hidden');
            darkIcon.classList.remove('hidden');
        } else {
            // 浅色模式：显示全月图标
            lightIcon.classList.remove('hidden');
            darkIcon.classList.add('hidden');
        }
    }

    initializeDarkMode() {
        const isDark = localStorage.getItem('darkMode') === 'true';
        if (isDark) {
            document.documentElement.classList.add('dark');
        }
        this.updateThemeIcon(isDark);
    }

    toggleDarkMode() {
        const isDark = document.documentElement.classList.toggle('dark');
        localStorage.setItem('darkMode', isDark.toString());
        this.updateThemeIcon(isDark);
    }

    // 搜索功能
    handleSearch(query) {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => {
            this.filterTemplates(query);
        }, 300);
    }

    filterTemplates(query) {
        if (!query.trim()) {
            this.filteredTemplates = [...this.templates];
        } else {
            const searchTerm = query.toLowerCase();
            this.filteredTemplates = this.templates.filter(template => 
                template.id.toLowerCase().includes(searchTerm) ||
                template.description.toLowerCase().includes(searchTerm) ||
                template.sql_template.toLowerCase().includes(searchTerm)
            );
        }
        this.renderTemplates();
    }

    // 数据加载
    async loadTemplates() {
        try {
            this.showLoading();
            const response = await authenticatedFetch('/api/v0/list_all_sql_templates');
            const data = await response.json();
            
            if (data.type === 'df') {
                this.templates = data.df;
                this.filteredTemplates = [...this.templates];
                this.renderTemplates();
                this.updateTemplateCount();
            } else {
                throw new Error(data.error || '加载失败');
            }
        } catch (error) {
            console.error('加载模板失败:', error);
            this.showError('加载模板失败');
        } finally {
            this.hideLoading();
        }
    }

    // 模板删除
    async deleteTemplate(id) {
        try {
            const response = await authenticatedFetch(`/api/v0/sql_templates/${id}`, {
                method: 'DELETE'
            });
            
            if (response.ok) {
                this.showSuccess('模板删除成功');
                await this.loadTemplates();
            } else {
                const data = await response.json();
                throw new Error(data.error || '删除失败');
            }
        } catch (error) {
            console.error('删除模板失败:', error);
            this.showError('删除模板失败');
        }
    }

    confirmDelete() {
        if (this.currentDeleteId) {
            this.deleteTemplate(this.currentDeleteId);
            this.hideDeleteModal();
        }
    }

    // 清空所有模板
    async clearAllTemplates() {
        try {
            this.showLoading();
            
            // 获取所有模板ID
            const templateIds = this.templates.map(template => template.id);
            
            if (templateIds.length === 0) {
                this.showError('没有模板需要删除');
                return;
            }

            // 批量删除所有模板
            const deletePromises = templateIds.map(id => 
                authenticatedFetch(`/api/v0/sql_templates/${id}`, {
                    method: 'DELETE'
                })
            );

            const results = await Promise.allSettled(deletePromises);
            
            // 检查删除结果
            const failedCount = results.filter(result => 
                result.status === 'rejected' || !result.value?.ok
            ).length;
            
            if (failedCount === 0) {
                this.showSuccess(`成功删除 ${templateIds.length} 个模板`);
            } else {
                this.showError(`删除完成，但有 ${failedCount} 个模板删除失败`);
            }
            
            // 重新加载模板列表
            await this.loadTemplates();
            
        } catch (error) {
            console.error('清空模板失败:', error);
            this.showError('清空模板失败');
        } finally {
            this.hideLoading();
        }
    }

    showClearAllModal() {
        document.getElementById('clearAllModal').classList.remove('hidden');
    }

    hideClearAllModal() {
        document.getElementById('clearAllModal').classList.add('hidden');
    }

    confirmClearAll() {
        this.clearAllTemplates();
        this.hideClearAllModal();
    }

    // 工具方法
    updateTemplateCount() {
        this.templateCount.textContent = `共 ${this.templates.length} 个模板`;
    }

    showLoading() {
        this.loadingIndicator.classList.remove('hidden');
        this.emptyState.classList.add('hidden');
        this.noSearchResults.classList.add('hidden');
    }

    hideLoading() {
        this.loadingIndicator.classList.add('hidden');
    }

    showEmptyState() {
        this.emptyState.classList.remove('hidden');
        this.noSearchResults.classList.add('hidden');
    }

    hideEmptyState() {
        this.emptyState.classList.add('hidden');
    }

    showNoSearchResults() {
        this.noSearchResults.classList.remove('hidden');
        this.emptyState.classList.add('hidden');
    }

    hideNoSearchResults() {
        this.noSearchResults.classList.add('hidden');
    }

    showSuccess(message) {
        // 简单的成功提示实现
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 3000);
    }

    showError(message) {
        // 简单的错误提示实现
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 5000);
    }
}